﻿@using TD.Common.Kendo.Mvc5.Grid
@using TD.Common.Kendo.Mvc5.Common

@model TD.CTS.Data.Entities.Trial

@Html.Partial("EditorTemplates/TrialVersionEditor", Model)

@(Html.Kendo().Grid<TD.CTS.WebUI.Models.TrialProcedureViewModel>()
    .Name("ProceduresGrid")
    .Selectable(select => select.Type(GridSelectionType.Cell))
    .Editable()
    .Scrollable()
    .Columns(columns =>
    {
        columns.Buttons(buttons => 
            {
                buttons.HeaderCustom().Tag(TD.Common.Kendo.Mvc5.Common.ButtonTag.a).ImageCssClass("k-add").AddCssClass("td-add-proc").Title("Изменить список процедур"); 
                buttons.Delete(); 
            })
            .HeaderHtmlAttributes(new { style = "vertical-align:bottom;" })
            .HtmlAttributes(new { @class = "k-group-cell" }).Width(50).Locked(true);
        columns.ForeignKey(e => e.ProcedureCode, (System.Collections.IEnumerable)ViewBag.Procedures, "Code", "Name")
            .Width(250)
            .Filterable(false)
            .HeaderTemplate(@"<div style=""text-align:right;width:230px;"">
<a class='k-button k-button-icontext k-grid-addcolumn td-grid-button' title='Добавить визит' href='javascript: void(0)'><span class='k-icon k-add td-grid-button-image'></span></a>
</div>
<div style=""text-align:right;width:230px;"">Визиты</div>
<div>Процедуры</div>")
            .HtmlAttributes(new { @class = "k-group-cell k-header" }).Locked(true);

        var visits = (IEnumerable<TD.CTS.Data.Entities.TrialVisit>)ViewBag.Visits;
        foreach (var visit in visits)
        {
            columns.Template(e => { })
                .ClientTemplate("#= SelectedVisit(" + visit.Id + ", data) #")
                .HeaderTemplate(string.Format(@"<div style='text-align:center;'><a class='k-button k-button-icontext td-grid-editcolumn td-grid-button' href='javascript: void(0)' title='Изменить визит'><span class='k-icon k-edit td-grid-button-image'></span></a>
<a class='k-button k-button-icontext td-grid-deletecolumn td-grid-button' href='javascript: void(0)' title='Удалить визит'><span class='k-icon k-delete td-grid-button-image'></span></a><input type='hidden' value='{3}'/></div>
<div style=""text-align:center;"" title=""{0}"">{0}</div><div style=""text-align:center;"">{1}&plusmn;{2}</div>", visit.Name, visit.Days, visit.Punctuality, visit.Id))
                .HtmlAttributes(new { style = "text-align:center;" })
                .Width(100);

        }
        columns.Template(e => { }).ClientTemplate(" ").Width("100%").HtmlAttributes(new { @class = "k-group-cell" });

    })
    .DataSource(dataSource => dataSource
       .Ajax()
       .Model(model =>
       {
           model.Id(e => e.Id);
           model.Field(e => e.ProcedureCode).Editable(false);
       })
       .Read(read => read.Action("GetTrialProcedures", "Trials").Data("GetTrialCode"))
       .Destroy(destroy => destroy.Action("DeleteTrialProcedure", "Trials"))
       .Events(events => events.Error("OnProcedureError"))//.RequestEnd("RequestEnd"))
    )
    .Events(events => events.Change("OnChange"))
)

@(Html.Kendo().Window()
    .Name("VisitEdit")
    .Modal(true)
    .Draggable(true)
    .Title("Визит")
    .HtmlAttributes(new { @class = "k-popup-edit-form" })
    .Visible(false)
    .Events(events => events.Refresh("OpenVisitEdit"))
)

@(Html.Kendo().Window()
    .Name("ProceduresWindow")
    .Modal(true)
    .Title("Процедуры")
    .HtmlAttributes(new { @class = "k-popup-edit-form" })
    .Visible(false)
    .Events(e => e.Activate("OnProceduresWindowActivate"))
    .Content(@<text>@Html.Partial("EditorTemplates/SelectProceduresEditor")</text>)
)

@(Html.Kendo().Window()
    .Name("VisitMaterialsWindow")
    .Modal(true)
    .Title("Процедуры")
    .HtmlAttributes(new { @class = "k-popup-edit-form" })
    .Visible(false)
    .Events(e => e.Activate("OnVisitMaterialsWindowActivate"))
    .Content(@<text>
        @(Html.Kendo().Grid<TD.CTS.WebUI.Models.TrialVisitMaterialViewModel>()
        .Name("VisitMaterialsGrid")
        .Editable()
        .AutoBind(false)
        .Scrollable()
        .Columns(columns =>
        {
            columns.Buttons(buttons =>
            {
                buttons.Add();
                buttons.Delete();
            }).Width(50).HeaderHtmlAttributes(new { style = "text-align:right;" });
            columns.Bound(e => e.TrialMaterialId)
                .ClientTemplate("#= MaterialName #")
                .EditorTemplateName("VisitMaterialEditor")
                .Width("100%").Title("Наименование материала");
            //columns.Bound(e => e.Quantity).Width(120).Title("Количество");
            //columns.Template(e => { }).ClientTemplate(" ").Width("100%");
        })
        .DataSource(dataSource => dataSource
           .Ajax()
           .Model(model =>
           {
               model.Id(e => e.Id);
               //model.Field(e => e.Quantity).DefaultValue(1);
           })
           .Read(read => read.Action("GetTrialVisitMaterials", "Trials").Data("VisitMaterialsData"))
           .Create(create => create.Action("AddTrialVisitMaterial", "Trials"))
           .Destroy(destroy => destroy.Action("DeleteTrialVisitMaterial", "Trials"))
           .Events(events => events.Error("kendo_grid_error_handler").RequestEnd("OnVisitMaterialRequestEnd"))
        )
        .Events(events => events
            .Edit("OnVisitMaterialEdit")
            .Save("OnVisitMaterialsSave")
            .Cancel("OnVisitMaterialCancel"))
        )
    </text>)
)

<script>
    var procGrid = $("#ProceduresGrid");

    procGrid.on("click", ".td-add-proc", function () {
        ShowProceduresWindow();
    });

    procGrid.on("click", ".td-visitMaterials", function () {
        ShowVisitMaterialsWindow();
    });

    procGrid.on("click", ".k-grid-addcolumn.td-grid-button", function () {
        ClearSelection();
        LoadVisitEdit();
    });

    procGrid.on("click", ".td-grid-editcolumn.td-grid-button", function () {
        ClearSelection();
        var id = $(this).parent().find("input").val();
        LoadVisitEdit(id);
    });

    procGrid.on("click", ".td-grid-deletecolumn.td-grid-button", function () {
        ClearSelection();
        var id = $(this).parent().find("input").val();
        DeleteVisit(id);
    });

    $("#VisitMaterialsGrid .k-grid-add.td-grid-button").click(function () {
        kendo_grid_createrow($("#VisitMaterialsGrid"));
    });

</script>

@* Procedures *@
<script>
    function ShowProceduresWindow() {
        ClearSelection();
        $("#SelectProceduresGrid").data("kendoGrid").dataSource.read();
        var window = $("#ProceduresWindow").data("kendoWindow");
        window.open().maximize();
    }

    function OnProceduresWindowActivate(e) {
        var emptyHeight = GetEmptyHeight($("#ProceduresWindow .k-edit-buttons"));
        var gridContent = $("#SelectProceduresGrid .k-grid-content");
        gridContent.height(gridContent.height() + emptyHeight - 16);
    }

    var NotChange = false;
    function OnChange(e) {
        if (NotChange)
            return;

        OnSelect($("#ProceduresGrid").data("kendoGrid"));
    }

    function GetTrialProcedureId() {
        var jGrid = $("#ProceduresGrid");
        var grid = jGrid.data("kendoGrid");
        var data = grid.dataItem(jGrid.find(".k-grid-edit-row"));
        return { trialProcedureId: data.Id };
    }

    function OnProcedureError(e) {
        $('#ProceduresGrid').data("kendoGrid").cancelChanges();
        kendo_grid_error_handler(e);
    }

</script>

@* Visits *@
<script>
    function LoadVisitEdit(id) {
        var window = $("#VisitEdit").data("kendoWindow");
        window.refresh({
            url: "@Url.Action("GetVisitEditor", "Trials")",
            data: { Id: id, TrialCode: $("#Code").val(), TrialVersion: $("#Version").data("kendoDropDownList").value() }
        });
    }

    var visitValidator;
    function OpenVisitEdit() {
        var visitWindow = $("#VisitEdit").data("kendoWindow");
        visitValidator = $("#visitForm").kendoValidator().data("kendoValidator");
        visitWindow.center().open();
        $("#cancelVisit").click(function () {
            visitWindow.close();
        });
        $("#saveVisit").click(function () {
            if (visitValidator.validate()) {
                var form = $("#visitForm");
                var isNew = form.find("#IsNew").val();
                $.ajax({
                    type: "POST",
                    url: isNew === "True" ? "@Url.Action("AddTrailVisit", "Trials")" : "@Url.Action("UpdateTrailVisit", "Trials")",
                    data: {
                        Id: form.find("#Id").val(),
                        Name: form.find("#Name").val(),
                        TrialCode: form.find("#TrialCode").val(),
                        TrialVersion: form.find("#TrialVersion").val(),
                        Days: form.find("#Days").val(),
                        Punctuality: form.find("#Punctuality").val()
                    },
                    success: function (result) {
                        $("#TabStrip-1").html(result);
                        $(window).trigger('resize');
                        visitWindow.close();
                    },
                    error: AjaxError
                });
            }
        });
    }

    function DeleteVisit(id) {
        if (confirm("Вы действительно хотите удалить визит?")) {
            $.ajax({
                type: "POST",
                url: "@Url.Action("DeleteTrailVisit", "Trials")",
                data: { Id: id, TrialCode: $("#Code").val(), TrialVersion: $("#Version").data("kendoDropDownList").value() },
                success: function (result) {
                    $("#TabStrip-1").html(result);
                },
                error: AjaxError
            });
        }
    }
</script>

@* Checkboxes *@
<script>
    var selectedCell;

    function SelectedVisit(visitId, data) {
        var index = GetVisitIndex(visitId, data.Visits);
        if (index !== -1)
            return '<input class="td-visit-checkbox" type="checkbox" dataId="' + data.Visits[index].Id +
                '" value="' + visitId + '" checked style="display:none;margin:0;width:24px;height:24px;" /><span class="k-icon k-i-tick"></span>' +
                '@(Html.Raw(Html.Kendo().ImageButton()
                    .AddCssClass("td-visitMaterials")
                    .ImageCssClass("k-edit")
                    .HtmlAttributes(new { style = "display:none;margin-top:-19px;" }).ToHtmlString()))';

        return "<input class=\"td-visit-checkbox\" type=\"checkbox\" value=\"" + visitId + "\" style=\"display:none;margin:0;width:24px;height:24px;\" />";
    }

    function GetVisitIndex(visitId, visits) {
        if (!visits)
            return -1;
        for (var i = 0, len = visits.length; i < len; i++) {
            if (visits[i].TrialVisitId === visitId)
                return i;
        }

        return -1;
    }

    function Update(endEdit) {
        var result = true;
        if (selectedCell != null) {
            var input = selectedCell.find("input");
            var checked = input.is(':checked');
            var visitId = parseInt(input.val());
            var row = selectedCell.closest("tr");
            var grid = $("#ProceduresGrid").data("kendoGrid");
            var rowData = grid.dataItem(row);
            var index = GetVisitIndex(visitId, rowData.Visits);
            if ((checked && index !== -1) || (!checked && index === -1)) {
                selectedCell.html(SelectedVisit(visitId, rowData));
                return result;
            }

            var data;
            var url;
            if (checked) {
                data = {
                    TrialVisitId: visitId,
                    ProcedureCode: rowData.ProcedureCode,
                    TrialCode: rowData.TrialCode,
                    TrialVersion: rowData.TrialVersion
                };
                url = "@Url.Action("AddTrialProcedureVisit", "Trials")";
            } else {
                data = { Id: input.attr("dataId") };
                url = "@Url.Action("DeleteTrialProcedureVisit", "Trials")";
            };

            $.ajax({
                type: "POST",
                url: url,
                data: data,
                async: false,
                success: function (newVisit) {
                    var rowIdx = $("tr", grid.tbody).index(row);
                    var colIdx = $("td", row).index(selectedCell);
                    if (checked) {
                        rowData.Visits.push(newVisit);
                    } else {
                        rowData.Visits.splice(index, 1);
                    }
                    grid.dataSource.pushUpdate(rowData);

                    selectedCell = $(grid.tbody[0].rows[rowIdx].cells[colIdx]);

                    //UpdateVisitMaterials();
                    var saveNotification = $("#SaveNotification").data("kendoNotification");
                    saveNotification.show("Сохранено", "success");
                },
                error: function (error) {
                    result = false;
                    AjaxError(error);
                    endEdit = false;
                }
            });

            if (!endEdit) {
                NotChange = true;
                grid.select(selectedCell);
                OnSelect(grid);
                NotChange = false;
            }
        }

        return result;
    }

    function OnSelect(grid) {
        var cell = grid.select();
        if (selectedCell != null) {
            if (!NotChange && cell.length > 0 && selectedCell.html() === cell.html())
                return;
            var input = selectedCell.find("input");
            var visitId = parseInt(input.val());
            var row = selectedCell.closest("tr");
            var grid = $("#ProceduresGrid").data("kendoGrid");
            var rowData = grid.dataItem(row);
            selectedCell.html(SelectedVisit(visitId, rowData));
        }
        if (cell.length > 0) {
            cell.find("input").css("display", "inline-block");
            cell.find("button").css("display", "inline-block");
            cell.find("span:eq(0)").remove();
            selectedCell = cell;
        } else {
            selectedCell = null;
        }

        //UpdateVisitMaterials();
    }

    function ClearSelection() {
        var grid = $("#ProceduresGrid").data("kendoGrid");
        if (selectedCell != null) {
            var input = selectedCell.find("input");
            var visitId = parseInt(input.val());
            var row = selectedCell.closest("tr");
            var grid = $("#ProceduresGrid").data("kendoGrid");
            var rowData = grid.dataItem(row);
            selectedCell.html(SelectedVisit(visitId, rowData));
        }
        grid.clearSelection();
        //UpdateVisitMaterials();
    }

    $("#ProceduresGrid").on("change", ".td-visit-checkbox", function () {
        if (!Update())
            $(this).attr("checked", !($(this).is(":checked")));
    });
</script>

@* VisitMaterials *@
<script>
    var visitMaterialsData = null;
    function ShowVisitMaterialsWindow() {
        if (selectedCell == null) {
            visitMaterialsData = null;
            return;
        }

        var input = selectedCell.find("input");
        var checked = input.is(':checked');

        if (!checked) {
            visitMaterialsData = null;
            return;
        }

        var visitMaterialId = input.attr("dataId");

        var grid = $("#VisitMaterialsGrid").data("kendoGrid");
        visitMaterialsData = { TrialVisitProcedureId: visitMaterialId };
        grid.dataSource.read();

        var window = $("#VisitMaterialsWindow").data("kendoWindow");
        window.open().maximize();
    }

    function OnVisitMaterialsWindowActivate(e) {
        var gridContent = $("#VisitMaterialsGrid .k-grid-content");
        var emptyHeight = GetEmptyHeight(gridContent);
        gridContent.height(gridContent.height() + emptyHeight);
    }

    function VisitMaterialsData() {
        return visitMaterialsData;
    }

    function OnVisitMaterialsSave(e) {
        e.model.TrialVisitProcedureId = visitMaterialsData.TrialVisitProcedureId;
        e.model.TrialCode = $("#Code").val();
    }

    function OnVisitMaterialEdit(e) {
        kendo_grid_resizeColumn($('#VisitMaterialsGrid'), 0, "75px");

        e.container.find("a.k-grid-delete").closest("td").html('<a class="k-button k-button-icontext k-primary k-grid-update td-grid-button" href="#" title="Обновить"><span class="k-icon k-update td-grid-button-image"></span></a>' +
                    '<a class="k-button k-button-icontext k-grid-cancel td-grid-button" href="#" title="Отмена"><span class="k-icon k-cancel td-grid-button-image"></span></a>');
    }

    function OnVisitMaterialCancel(e) {
        kendo_grid_resizeColumn($('#VisitMaterialsGrid'), 0, "50px");
    }

    function OnVisitMaterialRequestEnd(e) {
        if (e.type === "update" || e.type === "create") {
            kendo_grid_resizeColumn($('#VisitMaterialsGrid'), 0, "50px");
        }
    }
</script>

<style>
    #ProceduresGrid tr td {
        border-width: 0 0 1px 1px;
    }

    #ProceduresGrid .k-grid-content td{
        padding:1px;
    }

    #ProceduresWindow, #VisitMaterialsWindow{
        padding: 0;
    }

    #ProceduresWindow .k-edit-buttons{
        bottom: 0;
        border-width: 0;
    }
</style>